package com.beauty.dressing.common.video;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.media.AudioManager;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

import com.framework.common.utils.ILog;

/**
 * @author qbw
 * @createtime 2016/05/19 16:29
 */


public abstract class PlayerGestureListener extends GestureDetector.SimpleOnGestureListener {

    /**
     * 没有点在video上
     */
    public static final int LOCATION_VIDEO_INVALID = -1;
    /**
     * 点在video左边
     */
    public static final int LOCATION_VIDEO_BRIGHTNESS = 0;
    /**
     * 点在video右边
     */
    public static final int LOCATION_VIDEO_VOLUME = 1;

    /**
     * 点在video上，拖动进度的时候
     */
    public static final int LOCATION_VIDEO = 2;

    /**
     * 手势阻力
     */
    private final float GESTURE_DRAG = 1000f;

    /**
     * action down事件是否触发在videoview上（如果不在videoview上就不处理）
     */
    private int mActionDown = LOCATION_VIDEO_INVALID;

    /**
     * 当前正在处理哪个事件
     */
    private int mActionHandle = LOCATION_VIDEO_INVALID;

    /**
     * 视频进度位置
     */
    private int mVideoProgressPosition;

    /**
     * down时候的坐标
     */
    private float mXDownPosition;
    private float mYDownPosition;
    /**
     * 水平方向：true，可以处理移动事件了；false，不可以处理（误触）
     */
    private boolean mHActivate;
    /**
     * 垂直方向：true，可以处理移动事件了；false，不可以处理（误触）
     */
    private boolean mVActivate;

    /**
     * 更新之后的量度百分比
     */
    private float mNewBrightnessPercent;

    /**
     * 当前调整声音的距离
     */
    private float mCurrVolumeDistance;

    /**
     * 更新之后的音量大小
     */
    private int mCurrVolume;

    protected Activity mActivity;

    protected AudioManager mAudioManager;

    protected int mMaxVolume;

    public PlayerGestureListener(Activity activity) {
        mActivity = activity;
        mAudioManager = (AudioManager) mActivity.getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        mXDownPosition = e.getX();
        mYDownPosition = e.getY();
        mHActivate = false;
        mVActivate = false;
        mActionDown = LOCATION_VIDEO_INVALID;
        mActionHandle = LOCATION_VIDEO_INVALID;
        if (canHandleEvent()) {
            mCurrVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            mVideoProgressPosition = getVideoCurrentProgressPosition();
            mActionDown = actionLocation((int) e.getX(), (int) e.getY());
        } else {
            ILog.lw("[vp]can not handle event");
        }
        return LOCATION_VIDEO_INVALID != mActionDown ? true : super.onDown(e);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {//单击
        ILog.ld("[vp]onSingleTapConfirmed");
        onPlayAreaClick();
        return super.onSingleTapConfirmed(e);
    }

    @Override
    public boolean onDoubleTap(MotionEvent e) {//双击
        ILog.ld("[vp]onDoubleTap");
        onPlayAreaDoubleClick();
        return super.onDoubleTap(e);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        int xoffset = (int) Math.abs(e2.getX() - mXDownPosition);
        int yoffset = (int) Math.abs(e2.getY() - mYDownPosition);
        if (Math.abs(distanceX) >= Math.abs(distanceY)) {//x方向移动的位移大于y方向
            if (xoffset >= 3 || mHActivate) {
                mHActivate = true;
                if (isVideoPrepared()) {
                    if (LOCATION_VIDEO_INVALID == mActionHandle || LOCATION_VIDEO == mActionHandle) {
                        updateVideoProgressUi(mVideoProgressPosition -= (distanceX * GESTURE_DRAG));
                    }
                }
            }
        } else {
            if (yoffset >= 2 || mVActivate) {
                mVActivate = true;
                switch (mActionDown) {
                    case LOCATION_VIDEO_BRIGHTNESS://亮度
                        if (LOCATION_VIDEO_INVALID == mActionHandle || LOCATION_VIDEO_BRIGHTNESS == mActionHandle) {
                            updateBrightness(distanceY / 100);
                        }
                        break;
                    case LOCATION_VIDEO_VOLUME://声音
                        if ((LOCATION_VIDEO_INVALID == mActionHandle || LOCATION_VIDEO_VOLUME == mActionHandle)) {
                            updateVolume(distanceY);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    public void onActionUp() {
        switch (mActionHandle) {
            case LOCATION_VIDEO:
                ILog.ld("[vp]LOCATION_VIDEO");
                updateVideoProgress(mVideoProgressPosition);
                break;
            case LOCATION_VIDEO_BRIGHTNESS:
            case LOCATION_VIDEO_VOLUME:
                ILog.ld("[vp]LOCATION_VIDEO_BRIGHTNESS, LOCATION_VIDEO_VOLUME");
                hideBrightnessOrVolumeLayout();
                break;
            default:
                break;
        }
    }

    /**
     * @param x
     * @param y
     * @return 点击在了video的哪一侧
     */
    protected int actionLocation(int x, int y) {
        Rect rect = videoPlayAreaRect();
        if (!rect.contains(x, y)) {
            return LOCATION_VIDEO_INVALID;
        }
        Rect leftRect = new Rect(rect.left, rect.top, rect.left + rect.width() / 2, rect.bottom);//左半部分
        if (leftRect.contains(x, y)) {
            return LOCATION_VIDEO_BRIGHTNESS;
        }
        Rect rightRect = new Rect(rect.left + rect.width() / 2, rect.top, rect.right, rect.bottom);//右半部分
        if (rightRect.contains(x, y)) {
            return LOCATION_VIDEO_VOLUME;
        }
        return LOCATION_VIDEO_INVALID;
    }

    /**
     * @return 是否可以处理事件
     */
    protected abstract boolean canHandleEvent();

    /**
     * @return 视频是否准备好可以播放了
     */
    protected abstract boolean isVideoPrepared();

    /**
     * @return 视频当前进度
     */
    protected abstract int getVideoCurrentProgressPosition();

    /**
     * 隐藏亮度或者声音的布局
     */
    protected abstract void hideBrightnessOrVolumeLayout();

    /**
     * @param tempNewPosition 视频拖动新的进度
     */
    protected void updateVideoProgressUi(int tempNewPosition) {
        mActionHandle = LOCATION_VIDEO;
    }

    protected void updateVideoProgress(int newPosition) {
        mActionHandle = LOCATION_VIDEO;
    }

    /**
     * 更新亮度
     */
    protected void updateBrightness(float percent) {
        try {
            mActionHandle = LOCATION_VIDEO_BRIGHTNESS;
            Window window = mActivity.getWindow();
            float brightnessPercent = window.getAttributes().screenBrightness;
            WindowManager.LayoutParams lpa = window.getAttributes();
            lpa.screenBrightness = brightnessPercent + percent;
            if (lpa.screenBrightness > 1.0f) {
                lpa.screenBrightness = 1.0f;
            } else if (lpa.screenBrightness < 0.1f) {
                lpa.screenBrightness = 0.1f;
            }
            window.setAttributes(lpa);
            mNewBrightnessPercent = lpa.screenBrightness;
            ILog.d("updateBrightness", "[liveplay]percent=" + percent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return 获取更新之后的亮度百分比
     */
    public float getNewBrightnessPercent() {
        return mNewBrightnessPercent;
    }

    /**
     * 更新音量
     *
     * @param yDistance y轴移动的距离
     */
    protected void updateVolume(float yDistance) {
        try {
            mActionHandle = LOCATION_VIDEO_VOLUME;
            int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (-1 == mCurrVolumeDistance) {//初始化
                mCurrVolumeDistance = volume * getMaxVolumeDistance() / mMaxVolume;
            }
            mCurrVolumeDistance += yDistance;
            if (mCurrVolumeDistance < 0) {
                mCurrVolumeDistance = 0;
            } else if (mCurrVolumeDistance > getMaxVolumeDistance()) {
                mCurrVolumeDistance = getMaxVolumeDistance();
            }
            mCurrVolume = (int) (mMaxVolume * (mCurrVolumeDistance / getMaxVolumeDistance()));
            if (mCurrVolume < 0) {
                mCurrVolume = 0;
            } else if (mCurrVolume > mMaxVolume) {
                mCurrVolume = mMaxVolume;
            }
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, mCurrVolume, 0);
            ILog.d("updateBrightness", "[liveplay]mCurrVolume=" + mCurrVolume);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected int getMaxVolumeDistance() {
        return 300;
    }

    public float getCurrVolumeDistance() {
        return mCurrVolumeDistance;
    }

    /**
     * @return 视频播放区域矩形
     */
    protected abstract Rect videoPlayAreaRect();

    protected abstract void onPlayAreaClick();

    protected abstract void onPlayAreaDoubleClick();
}
